package cn.com.yusys.yusp.admin.validation.ext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.yusys.yusp.admin.service.AdminSmLookupItemCacheService;
import cn.com.yusys.yusp.admin.service.AdminSmLookupItemClient;
import cn.com.yusys.yusp.admin.validation.InDataCode;

/**
 * 有效性校验.
 * 
 *
 * @author jiaxy2
 * @since 2.1.1
 */
public class InDataCodeValidator implements ConstraintValidator<InDataCode, String> {

    private String dataCode ;
    
    @Autowired
    private AdminSmLookupItemClient adminSmLookupItemClient;
    
    @Autowired
    AdminSmLookupItemCacheService adminSmLookupItemCacheService;
    
    @Override
    public void initialize(InDataCode constraintAnnotation) {
    	dataCode = constraintAnnotation.dataCode();
    }
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (null == value || "".equals(value)) {
            return true;
        }
        List<String> codes = new ArrayList<String>();
        Map<String, List<Map<String, String>>> LookupCodeMap = adminSmLookupItemCacheService.getLookupCodeCacheList(dataCode);
        if(LookupCodeMap != null && LookupCodeMap.containsKey(dataCode)) {
        	List<Map<String, String>> lookupItem = LookupCodeMap.get(dataCode);
        	if(lookupItem != null && lookupItem.size() >0) {
        		for(Map<String, String> map: lookupItem) {
        			codes.add(map.get("key"));
                }
        	}
        }else {
        	codes = adminSmLookupItemClient.getLookupItemCode(dataCode);
        }
        if(codes == null) {
        	//禁用默认提示语
        	context.disableDefaultConstraintViolation();
        	//设置提示语
        	context.buildConstraintViolationWithTemplate("Query data dictionary exception, please contact the administrator!").addConstraintViolation(); //查询数据字典异常，请联系管理员！
        	return false;
        }else if(codes.size() == 0) {
        	//禁用默认提示语
        	context.disableDefaultConstraintViolation();
        	//设置提示语
        	context.buildConstraintViolationWithTemplate("The data dictionary [dataCode:"+dataCode+"] corresponding to this field does not exist!").addConstraintViolation(); //该字段对应的数据字典【dataCode:{}】不存在！
        	return false;
        }
        return codes.contains(value);
    }
}
